package com.visionet.school.app.web.common.filter;

import com.visionet.school.app.web.common.web.DefaultWebContext;
import com.visionet.school.app.web.common.web.WebContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by hxpeng on 2017/4/29.
 */
public class WebContextFilter extends HttpServlet implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(WebContextFilter.class);


    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.info("进入拦截");
        DefaultWebContext ctx = (DefaultWebContext) WebContextFactory.getWebContext();
        WebContextFactory.setContext(request.getServletContext());
        if(request instanceof HttpServletRequest && response instanceof HttpServletResponse){
            ctx.setRequest((HttpServletRequest)request);
            ctx.setResponse((HttpServletResponse)response);
            ctx.setSession(((HttpServletRequest) request).getSession());
        }
        logger.info("退出拦截");
        chain.doFilter(request, response);
    }

    public void destroy() {}
}
